package cn.edu.imut.dao;

import cn.edu.imut.bean.UserBean;
import cn.edu.imut.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 注册用户
     */
    public boolean register(UserBean user) {
        String sql = "INSERT INTO gs_users (username, password, phone, address, purchase_history, account_balance, role) VALUES (?, ?, ?, ?, ?, ?, ?)";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getPhone());
            pstmt.setString(4, user.getAddress());
            pstmt.setString(5, user.getPurchaseHistory());
            pstmt.setDouble(6, user.getAccountBalance());
            pstmt.setString(7, user.getRole()); // 新增字段 role
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("用户注册失败：" + e.getMessage());
        }
        return false;
    }

    /**
     * 用户登录
     */
    public UserBean login(String username, String password) {
        String sql = "SELECT * FROM gs_users WHERE username = ? AND password = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return new UserBean(
                        rs.getInt("user_id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("phone"),
                        rs.getString("purchase_history"),
                        rs.getDouble("account_balance"),
                        rs.getString("address"),
                        rs.getString("role") // 新增字段 role
                );
            }
        } catch (Exception e) {
            System.err.println("用户登录失败：" + e.getMessage());
        }
        return null;
    }

    /**
     * 根据用户名获取用户信息
     */
    public UserBean getUserByUsername(String username) {
        String sql = "SELECT * FROM gs_users WHERE username = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return new UserBean(
                        rs.getInt("user_id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("phone"),
                        rs.getString("purchase_history"),
                        rs.getDouble("account_balance"),
                        rs.getString("address"),
                        rs.getString("role") // 新增字段 role
                );
            }
        } catch (Exception e) {
            System.err.println("获取用户信息失败：" + e.getMessage());
        }
        return null;
    }

    /**
     * 找回密码
     */
    public boolean recoverPassword(String username, String phone) {
        String sql = "SELECT * FROM gs_users WHERE username = ? AND phone = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, phone);
            ResultSet rs = pstmt.executeQuery();
            return rs.next();
        } catch (Exception e) {
            System.err.println("验证用户名和手机号失败：" + e.getMessage());
        }
        return false;
    }

    /**
     * 重置密码
     */
    public boolean resetPassword(String username, String newPassword) {
        String sql = "UPDATE gs_users SET password = ? WHERE username = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, newPassword);
            pstmt.setString(2, username);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("重置密码失败：" + e.getMessage());
        }
        return false;
    }

    /**
     * 更新用户信息
     */
    public boolean updateUser(UserBean user) {
        String sql = "UPDATE gs_users SET phone = ?, address = ? WHERE username = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getPhone());
            pstmt.setString(2, user.getAddress());
            pstmt.setString(3, user.getUsername());
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("更新用户信息失败：" + e.getMessage());
        }
        return false;
    }

    /**
     * 获取所有用户信息
     */
    public List<UserBean> getAllUsers() {
        List<UserBean> users = new ArrayList<>();
        String sql = "SELECT * FROM gs_users";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                users.add(new UserBean(
                        rs.getInt("user_id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("phone"),
                        rs.getString("purchase_history"),
                        rs.getDouble("account_balance"),
                        rs.getString("address"),
                        rs.getString("role") // 新增字段 role
                ));
            }
        } catch (Exception e) {
            System.err.println("获取所有用户信息失败：" + e.getMessage());
        }
        return users;
    }

    /**
     * 更新用户权限
     */
    public boolean updateUserRole(int userId, String role) {
        String sql = "UPDATE gs_users SET role = ? WHERE user_id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, role);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("更新用户角色失败：" + e.getMessage());
        }
        return false;
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param userID 用户ID
     * @return UserBean 对象，若未找到用户则返回 null
     */
    public UserBean getUserByUserID(final int userID) {
        String sql = "SELECT * FROM gs_users WHERE user_id = ?";
        UserBean user = null;

        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, userID);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                user = new UserBean(
                        resultSet.getInt("user_id"),
                        resultSet.getString("username"),
                        resultSet.getString("password"),
                        resultSet.getString("phone"),
                        resultSet.getString("purchase_history"),
                        resultSet.getDouble("account_balance"),
                        resultSet.getString("address"),
                        resultSet.getString("role")
                );
            }
        } catch (Exception e) {
            System.err.println("查询用户信息时发生错误：" + e.getMessage());
            e.printStackTrace();
        }

        return user;
    }
}
